/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nxtgeninventorysystem.Controller;

import nxtgeninventorysystem.Model.Database;
import nxtgeninventorysystem.View.Dialog.DatabaseConfig;
import nxtgeninventorysystem.View.Gui;
import nxtgeninventorysystem.View.Gui.Dialog;

/**
 *
 * @author MSI
 */
public final class DatabaseActions extends Actions {

    public DatabaseActions() {

    }

    public void connectToDatabase() {
        DatabaseConfig form = (DatabaseConfig) Gui.getDialog(Dialog.DatabaseConfiguration);
        form.setConnecting(true);
        Thread guiThread = new Thread() {
            public void run() {
                DatabaseConfig form = (DatabaseConfig) Gui.getDialog(Dialog.DatabaseConfiguration);

                Actions.database.setDatabaseConfig();

                form.setEnabled(false);

                Thread connectThread = new Thread() {
                    public void run() {
                        Database.connectToDatabase();
                        Gui.refreshComboBoxes(Database.item.readItemTypes(), Database.person.readTeams());
                    }
                };

                Gui.setStatusBarMessage("Connecting to database...");
                Gui.setBusyEffect(true);
                connectThread.start();

                while(connectThread.isAlive()) {

                }

                if(Database.isConnected()) {
                    Gui.setStatusBarMessage("Connected to database...");
                    Gui.setBusyEffect(false);
                }
                else {
                    Gui.setStatusBarMessage("Cannot connect to database...");
                    Gui.setBusyEffect(false);
                }
                form.setConnecting(false);
                form.setEnabled(true);
            }
        };
        guiThread.start();
    }

    public void setDatabaseConfig() {
        DatabaseConfig form = (DatabaseConfig) Gui.getDialog(Dialog.DatabaseConfiguration);
        Database.setDatabase(form.getDatabase());
        Database.setHostname(form.getHostname());
        Database.setPassword(form.getPassword());
        Database.setPort(form.getPort());
        Database.setUsername(form.getUsername());
    }

    public void saveDatabaseConfig() {
        setDatabaseConfig();
        Database.saveConnectionOptions();
    }

    public void reflectDatabaseFields() {
        DatabaseConfig form = (DatabaseConfig) Gui.getDialog(Dialog.DatabaseConfiguration);
        form.setDatabase(Database.getDatabase());
        form.setHostname(Database.getHostname());
        form.setPassword(Database.getPassword());
        form.setPort(Database.getPort());
        form.setUsername(Database.getUsername());
    }

}
